package com.itheima.exception;

import com.itheima.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.sql.SQLIntegrityConstraintViolationException;

/**
 * @author Tang
 * @date 2023/2/20
 */
//全局异常处理类
//作用：可以捕获所有控制器类中出现的异常
    //一般和@ExceptionHandler注解配合使用
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandle {

    //处理可预料的异常
    @ExceptionHandler(CustomException.class)  //指定要处理的异常类
    public R<String> doCustomException(CustomException ex) {
        log.warn(ex.getMessage());
        return R.error(ex.getMessage());
    }

    /**
     * 异常处理方法
     * @return
     */
    @ExceptionHandler(SQLIntegrityConstraintViolationException.class)
    public R<String> doSQLException(SQLIntegrityConstraintViolationException ex){
        log.error(ex.getMessage());
        if(ex.getMessage().contains("Duplicate entry")){
            String[] split = ex.getMessage().split(" ");
            String msg = split[2] + "已存在";
            return R.error(msg);
        }
        return R.error("未知错误");
    }
}
